<?php

/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
namespace app\domain\admin;

use app\common\builder\ZBuilder;
use app\admin\controller\Admin;
use app\domain\model\Domain as DomainModel;
use app\admin\model\Menu as MenuModel;
use util\Tree;
use think\Db;

/**
 * 套餐管理
 * @package app\admin\controller
 */
class Index extends Admin{
    public function index()
    {
      
        
        $map = $this->getMap();
        // 排序
        $order = $this->getOrder('status asc,id desc');
        $map['delete'] = 0;
        // 数据列表
        $data_list = DomainModel::where($map)->order($order)->paginate();
        // 加入角色
        $role = session('user_auth.role');
        $uid = session('user_auth.uid');
        return ZBuilder::make('table')
            ->addOrder('id') // 添加排序
            ->hideCheckbox()
            ->setSearch(['url' => '绑定域名','username' => '使用者','uniacid' => '商户id']) // 设置搜索框
            ->addColumns([ // 批量添加数据列
                ['id', 'ID'],
                ['url', '域名名称', 'text'],
                ['username', '使用者', 'text'],
                ['uniacid', '商户id', 'text'],
                ['create_time', '创建时间', 'text'],
                ['status', '状态','status', '', ['未使用', '已使用']],
                ['right_button', '操作', 'btn']
            ])
            ->addTopButtons('add') // 批量添加顶部按钮
            ->addRightButtons(['edit' => ['title' => '绑定域名'], 'delete' => ['data-tips' => '删除后无法恢复。']]) // 批量添加右侧按钮
            ->replaceRightButton(['status'=>['in','1']],'',['edit'])
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染模板
    }
    // 更换商户名称
    public function getname($uniacid){
          // $vdong_where['username'] = '';
        // $vdong_where['status'] = 1;
        // $data_list = Db::name('domain')->where($vdong_where)->select();
        //  // print_r($data_list);die;
        // foreach ($data_list as $k => $v) {

        //     $result = $this->getname($v['uniacid']);
        //     if($result['code']==1){
        //         $where['uniacid'] = $v['uniacid'];
        //         $where['id'] = $v['id'];
        //         $re['username'] = $result['name'];
        //         DomainModel::update($re,$where);
        //     }
            
        // }
        // die;
        $params['uniacid'] = $uniacid;
        $opts = [
            CURLOPT_TIMEOUT        => 20,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_URL            => 'https://wxapis.vdongchina.com/Catering/V2/refund/getDomainTitle',
            CURLOPT_USERAGENT      => $_SERVER['HTTP_USER_AGENT'],
            CURLOPT_POST           => 1,
            CURLOPT_POSTFIELDS     => $params
        ];

        // 初始化并执行curl请求
        $ch = curl_init();
        curl_setopt_array($ch, $opts);
        $result  = curl_exec($ch);
        curl_close($ch);
        $result = json_decode($result, true);
        if ($result['code']==0) {
            $reurn_data['name'] = $result['Response']['name'];
            $reurn_data['code'] = 1;
            return $reurn_data;
        } else {
            $this->error($result['result']);
        }
        
    }

    /**
     * 添加套餐
     * @return mixed
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $num = $data['num'];
            $type = $data['type'];
            $root_host = $data['root_host'];
            $position =  $data['position'];
            for ($i=0; $i < $num; $i++) { 
                $RR = rand(10000001,99999999);
                if($type==3){
                    if($position=='weixin'){
                       $vdong = 'wx'; 
                    }else{
                       $vdong = 'corp'; 
                    }
                    $RR = $vdong.'.'.$RR;
                }
                $com_res =  $this->compose_url($RR,$root_host,$position);
                if($com_res>0){
                    $domain['url']=$RR.'.'.$root_host;
                    $domain['create_time']=date('Y-m-d H:i:s',time());
                    $domain['status']=0;
                    $domain['delete']=0;
                    $domain['root_host']=$root_host;
                    $domain['type']=$type;
                    $domain['record_id']=$com_res;
                    DomainModel::create($domain);
                }
            }
            $this->success('生成成功');
        }
        // 菜单列表
        $type = ['2' => '二级域名', '3' => '三级域名'];
        $root_host = ['vdongchina.com' => 'vdongchina.com'];
        $position = ['weixin'=>'weixin','corp'=>'corp'];
        return ZBuilder::make('form')
            ->setPageTitle('生成域名') // 设置搜索框
            ->addFormItems([ // 批量添加数据列
                ['text', 'num', '生成数量', '必填，生成数量'],
                ['select', 'type', '类型', '必填，类型',$type],
                ['select', 'root_host', '根域名', '必填，根域名',$root_host],
                ['select', 'position', '指定位置', '必填，指定位置',$position],
            ])
            ->fetch(); // 渲染模板
    }
    /**
     * 编辑套餐
     * @param null $id
     * @return mixed
     */
    public function edit($id = null)
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $where['id'] = $data['id'];
            $binding_res = $this->binding($data);
            if($binding_res['code']==1){
                $re['status'] = 1;
                if($binding_res['name']){
                    $re['username'] = $binding_res['name'];
                }else{
                    $re['username'] = $data['username'];
                }
                $re['uniacid'] = $data['uniacid'];
                $re['use_time'] = date('Y-m-d H:i:s',time());
                if (DomainModel::update($re,$where)) {
                    $this->success('修改成功', url('index'));
                } else {
                    $this->error('修改失败');
                }
            }
        }
        $info = DomainModel::where('id', $id)->find();
        return ZBuilder::make('form')
            ->setPageTitle('新增') // 设置页面标题
            ->addFormItems([ // 批量添加表单项
                ['hidden', 'id'],
                ['text', 'username', '使用者', '必填，使用者'],
                ['text', 'uniacid', '商户id'],
                ['text','url','域名地址','必填，域名地址'],
            ])
            ->setFormData($info) // 设置表单数据
            ->fetch();
        
    }
    // 绑定域名
    public function binding($data){

        $params['uniacid'] = $data['uniacid'];
        $params['url'] = $data['url'];
        $opts = [
            CURLOPT_TIMEOUT        => 20,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_URL            => 'https://wxapis.vdongchina.com/Catering/V2/refund/setDomainUrl',
            CURLOPT_USERAGENT      => $_SERVER['HTTP_USER_AGENT'],
            CURLOPT_POST           => 1,
            CURLOPT_POSTFIELDS     => $params
        ];

        // 初始化并执行curl请求
        $ch = curl_init();
        curl_setopt_array($ch, $opts);
        $result  = curl_exec($ch);
        curl_close($ch);
        $result = json_decode($result, true);
        if ($result['code']==0) {
            $reurn_data['name'] = $result['Response']['name'];
            $reurn_data['code'] = 1;
            return $reurn_data;
        } else {
            $this->error($result['result']);
        }
        
    }
    public function delete($record = [])
    {
        $param = $this->request->param();
        $ids = $param['ids'];
        $where['id'] = $ids;
        if (is_array($ids)) {
            $where['id'] = array('in', $ids);
        }
        $data['delete'] = 1;
         $info = DomainModel::where($where)->find();
        $com_res =  $this->delete_url($info['record_id']);
        if($com_res>0){
            if (DomainModel::update($data, $where)) {
                $this->success('删除成功', url('index'));
            } else {
                $this->error('删除失败');
            }
        }else{
            $this->error('删除失败');
        }

        
    }
    public function percent_encode($res){
        $res=trim(utf8_encode(urlencode($res)));
        $res=str_replace(array('+','*','%7E'), array('%20','%2A','~'), $res);
        return $res;
    }
    public function uuid($prefix = '')  
      {  
        $chars = md5(uniqid(mt_rand(), true));  
        $uuid  = substr($chars,0,8) . '-';  
        $uuid .= substr($chars,8,4) . '-';  
        $uuid .= substr($chars,12,4) . '-';  
        $uuid .= substr($chars,16,4) . '-';  
        $uuid .= substr($chars,20,12);  
        return $prefix . $uuid;  
      } 
    public function compute_signature($parameters, $access_key_secret){
        ksort($parameters);
        $canonicalizedQueryString = '';
        foreach ($parameters as $k => $v) {
          if(empty($canonicalizedQueryString))
            $canonicalizedQueryString .= $this->percent_encode($k) . '=' . $this->percent_encode($v);
          else
             $canonicalizedQueryString .= '&' . $this->percent_encode($k) . '=' . $this->percent_encode($v);
        }    
        $stringToSign = 'GET&%2F&' . $this->percent_encode($canonicalizedQueryString);
        $signature=base64_encode(hash_hmac("sha1",$stringToSign,$access_key_secret."&",true));
        return $signature;     
    }
    // 域名删除解析
    public function delete_url($RecordId){
        $timestamp=gmdate("Y-m-d\TH:i:s\Z");
        $access_key_id='LTAIHXqFJXqzXTEl';
        $access_key_secret='SGNUBeFuAsVeipBboLi9YoZuYQk18K';
         $parameters = array(
                'Format'        => 'JSON', 
                'Version'       => '2015-01-09', 
                'AccessKeyId'   => $access_key_id, 
                'SignatureVersion'  => '1.0', 
                'SignatureMethod'   => 'HMAC-SHA1', 
                'SignatureNonce'    => $this->uuid(), 
                'Timestamp'         => $timestamp, 
                'Action'            =>'DeleteDomainRecord',
                'RecordId'        =>$RecordId, 

        );
        $signature = $this->compute_signature($parameters, $access_key_secret);
        $canonicalizedQueryString='Signature='.$signature;
        foreach ($parameters as $k => $v) {
             $canonicalizedQueryString .= '&' . $k . '=' . $this->percent_encode($v);
        }   
        $url = "http://alidns.aliyuncs.com/?".$canonicalizedQueryString;
        $res =$this->get_url($url);
        $resultArr = json_decode($res,true);
        if(isset($resultArr['Message'])){
            return 0;
        }
        if(isset($resultArr['RecordId'])){
            return $resultArr['RecordId'];
        }
        return 0;
        
    }
    // 域名解析
    public function compose_url($RR,$root_host,$position){
        $timestamp=gmdate("Y-m-d\TH:i:s\Z");
        $access_key_id='LTAIHXqFJXqzXTEl';
        $access_key_secret='SGNUBeFuAsVeipBboLi9YoZuYQk18K';
        $parameters = array(
                'Format'        => 'JSON', 
                'Version'       => '2015-01-09', 
                'AccessKeyId'   => $access_key_id, 
                'SignatureVersion'  => '1.0', 
                'SignatureMethod'   => 'HMAC-SHA1', 
                'SignatureNonce'    => $this->uuid(), 
                'Timestamp'         => $timestamp, 
                'Action'            =>'AddDomainRecord',//DescribeCdnService
                'DomainName'        =>$root_host, 
                'RR' =>$RR,
                'Type' => 'A',
                'Value' => '60.205.205.130',
                'Line' => 'default'

        );
        $signature = $this->compute_signature($parameters, $access_key_secret);
        $canonicalizedQueryString='Signature='.$signature;
        foreach ($parameters as $k => $v) {
             $canonicalizedQueryString .= '&' . $k . '=' . $this->percent_encode($v);
        }   
        $url = "http://alidns.aliyuncs.com/?".$canonicalizedQueryString;
        $res =$this->get_url($url);
        $resultArr = json_decode($res,true);
        if(isset($resultArr['Message'])){
            return 0;
        }
        if(isset($resultArr['RecordId'])){
            $this->vdongchina($RR,$root_host,$position);
            return $resultArr['RecordId'];
        }
        return 0;
        
    }
    public function get_url($url,$cookie=false){
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            $output = curl_exec($ch);
            curl_close($ch);
            return $output;
    }
    public function vdongchina($RR,$root_host,$position){
            if($position=='weixin'){
                $content = file_get_contents('./conf/weixin.vdongchina.com.conf');
            }else{
                $content = file_get_contents('./conf/corp.vdongchina.com.conf');
            }
            $preg = "corp";
            $data = str_replace($preg,$RR,$content);
            file_put_contents('./confnew/'.$RR.'.'.$root_host.'.conf', $data);
     }
}
